/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/core/{{modules}}/service/impl/{{entities@SQL}}ServiceImpl.java.hbs
 */
// @SkipOverwrite
package cn.ibizlab.core.authorization.service.impl;

import cn.ibizlab.core.ad.domain.SysOrganization;
import cn.ibizlab.core.ad.service.SysOrganizationService;
import cn.ibizlab.core.authorization.domain.SysRoleMember;
import cn.ibizlab.core.authorization.filter.SysRoleMemberSearchContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 实体[系统角色成员] 服务对象接口实现
 *
 * @author generator
 */
@Slf4j
@Service("SysRoleMemberService")
public class SysRoleMemberServiceImpl extends AbstractSysRoleMemberService {

    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Override
    public List<SysRoleMember> member(SysRoleMember dto) {
        SysRoleMemberSearchContext context =  new SysRoleMemberSearchContext();
        if(!ObjectUtils.isEmpty(dto.getDepartmentId()))
            context.setDepartmentIdEQ(dto.getDepartmentId());
        if(!ObjectUtils.isEmpty(dto.getOrganizationId())) {
            String orgId = dto.getOrganizationId();
            orgId = sysOrganizationService.findOrganizationId(new SysOrganization().setId(orgId).setDc(dto.getDc()));
            if(!ObjectUtils.isEmpty(orgId))
                context.setOrganizationIdEQ(orgId);
        }
        if(!ObjectUtils.isEmpty(dto.getMemberGroupId()))
            context.setMemberGroupIdEQ(dto.getMemberGroupId());
        if(!ObjectUtils.isEmpty(dto.getMemberName()))
            context.setMemberNameLIKE(dto.getMemberName());
        if(!ObjectUtils.isEmpty(dto.getMemberUid()))
            context.setMemberUidEQ(dto.getMemberUid());
        String roleId = dto.getId();
        if(ObjectUtils.isEmpty(roleId))
            roleId = dto.getRoleId();
        if(!ObjectUtils.isEmpty(roleId)) {
            if(roleId.indexOf(",")>=0) {
                context.set("role_ids",getCond(Arrays.asList(roleId.split(","))));
            }
            else
                context.set("role_id",roleId);
        }
        return this.listUsersByRoleId(context);
    }


    private String getCond(Collection<String> items) {
        return ObjectUtils.isEmpty(items)?null:"('"+String.join("','",items)+"')";
    }

    @Override
    public List<SysRoleMember> listByRoleIds(SysRoleMember dto) {
        return member(dto);
    }
}